import { Form } from 'antd';
import { FunctionComponent, useEffect, useState } from 'react';
import { NbFormItemScheme } from '../interface';
import useObservableForm from '../new/useObservableForm';
import NbObjectWidget from './object/object.widget';
import { widgets } from './widgets';

interface WidgetCellProps extends NbFormItemScheme {
  name?: string[];
}

export default function WidgetCell(cellProps: WidgetCellProps) {
  const {
    widget = 'input',
    properties = {},
    props = {},
    name = [],
    render,
    required,
    ...formItemProps
  } = cellProps;
  let Com: FunctionComponent<any> = render || widgets[widget];
  const [comProps, setComProps] = useState(props);
  const [itemProps, setItemProps] = useState<NbFormItemScheme>(formItemProps);
  const formName = name[0];
  const itemName = name.slice(1).join('.');
  const observableForm = useObservableForm(formName);
  const form = observableForm.form;

  function handleChange(value: any) {}

  if (!Com) {
    return <>控件不存在</>;
  }

  if (widget === 'object') {
    return <NbObjectWidget properties={properties} name={name} />;
  }

  return (
    <Form.Item
      name={name}
      rules={[{ required: itemProps.required }, ...(itemProps.rules ?? [])]}
      {...itemProps}
    >
      <Com {...props} onChange={handleChange} />
    </Form.Item>
  );
}
